<?php


use Biz\model\activity\PageModule;
use Biz\model\brandActivity\BlindBoxActivityPrize as mBlindBoxActivityPrize;
use Biz\model\wiki\Wiki as mWiki;
use Biz\service\activity\Page;
use Biz\service\brand\BlindBox;
use Biz\service\brand\BlindBoxLottery;
use Doraemon\service\Follow;
use Doraemon\service\User;
use Doraemon\tools\ImgUrl;
use Biz\cache\brand\BrandShowActivity;

/**
 * 打开盲盒
 */
class OpenBoxAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_REGISTER;

    public function main()
    {
        $boxId = $this->getRequest()->getPost('box_id', 0);
        $pageId = $this->getRequest()->getPost('page_id', 0);
        $boxMap = BlindBox::getBlindBox($this->uid);
        $allBoxId = array_keys($boxMap);
        if (!$boxId || !in_array($boxId, $allBoxId)) {
            throw new \Exception('参数错误');
        }
        try {
            Follow::FollowMultiUsers($this->uid, [User::HAOHAOZHUFULIGUAN_UID], 'blind_box');//关注好好住福利官
        } catch (\Exception $e) {
        }
        $this->checkPageId($pageId);
        if (!BrandShowActivity::isLock($this->uid . '-blind-box', 2)) {
            $result = BlindBoxLottery::openBox($this->uid, $boxId, $pageId);
            if ($result) {
                if (in_array($result['prize_type'], [mBlindBoxActivityPrize::PRIZE_TYPE_GOODS, mBlindBoxActivityPrize::PRIZE_TYPE_GOOD_COUPON]) && $result['basic_id']) {
                    $where = [
                        'status[!]' => mWiki::STATUS_DELETE,
                        'basic_id' => $result['basic_id'],
                        'is_default' => mWiki::IS_DEFAULT
                    ];
                    $info = mWiki::getByWhere($where);
//                    if ($info) {
//                        $result['open_other_link'] = Wiki::getOpenOtherLink($info);
//                    }
                } else if ($result['prize_type'] == mBlindBoxActivityPrize::PRIZE_TYPE_LIMIT_CARD) {
                    $result['prize_value'] = $result['prize_value'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $result['prize_value'], ImgUrl::IMAGE_SIZE_OP_ORI) : '';
                }
            }
            $result['user_info'] = User::getBasicUserInfo($this->uid);
            $this->setSuccess($result);
        } else {
            throw new \Exception('你的操作太频繁');
        }
    }

    private function checkPageId($pageId)
    {
        $result = true;
        if ($pageId > 0) {
            $result = false;
            $pageInfo = Page::getPageInfo($pageId);
            if ($pageInfo && $pageInfo['module_list']) {
                foreach ($pageInfo['module_list'] as $row) {
                    if ($row['type'] == PageModule::MODULE_TYPE_BLIND_BOX) {
                        $result = true;
                        break;
                    }
                }
            }
        }
        if (!$result) {
            throw new \Exception('活动已结束');
        }
    }
}